import zlib from 'zlib';

/**
 * 代理工具函数
 */
export class ProxyUtils {
  
  /**
   * 提取请求数据
   */
  static async extractRequestData(req, isHttps = false) {
    const url = isHttps ? `https://${req.headers.host}${req.url}` : `http://${req.headers.host}${req.url}`;
    
    return {
      id: null, // 由调用者设置
      url: url,
      method: req.method,
      headers: { ...req.headers },
      cookies: this.extractCookies(req.headers),
      body: null, // 由调用者设置
      timestamp: Date.now(),
      clientIp: req.socket.remoteAddress,
      httpVersion: req.httpVersion ? `HTTP/${req.httpVersion}` : 'HTTP/1.1'
    };
  }

  /**
   * 从请求头中提取Cookie
   */
  static extractCookies(headers) {
    const cookies = {};
    const cookieHeader = headers['cookie'] || headers['Cookie'];
    
    if (cookieHeader) {
      const cookiePairs = cookieHeader.split(';');
      cookiePairs.forEach(pair => {
        const [name, ...rest] = pair.trim().split('=');
        if (name && rest.length > 0) {
          cookies[name] = rest.join('=');
        }
      });
    }
    
    return cookies;
  }

  /**
   * 读取请求体
   */
  static readRequestBody(req) {
    return new Promise((resolve, reject) => {
      let body = '';
      req.on('data', chunk => {
        body += chunk.toString();
      });
      req.on('end', () => {
        resolve(body || null);
      });
      req.on('error', error => {
        reject(error);
      });
    });
  }

  /**
   * 同步解压响应体
   */
  static async decompressResponseBodySync(buffer, encoding) {
    if (!buffer || buffer.length === 0) {
      return '';
    }

    try {
      switch (encoding) {
        case 'gzip':
          return zlib.gunzipSync(buffer).toString('utf8');
        case 'deflate':
          return zlib.inflateSync(buffer).toString('utf8');
        case 'br':
          return zlib.brotliDecompressSync(buffer).toString('utf8');
        default:
          return buffer.toString('utf8');
      }
    } catch (error) {
      console.warn('⚠️ 同步解压失败，返回原始数据:', error.message);
      return buffer.toString('utf8');
    }
  }

  /**
   * 异步解压响应体
   */
  static async decompressResponseBody(buffer, encoding) {
    if (!buffer || buffer.length === 0) {
      return '';
    }

    return new Promise((resolve) => {
      try {
        switch (encoding) {
          case 'gzip':
            zlib.gunzip(buffer, (err, result) => {
              if (err) {
                console.warn('⚠️ gzip解压失败:', err.message);
                resolve(buffer.toString('utf8'));
              } else {
                resolve(result.toString('utf8'));
              }
            });
            break;
          case 'deflate':
            zlib.inflate(buffer, (err, result) => {
              if (err) {
                console.warn('⚠️ deflate解压失败:', err.message);
                resolve(buffer.toString('utf8'));
              } else {
                resolve(result.toString('utf8'));
              }
            });
            break;
          case 'br':
            zlib.brotliDecompress(buffer, (err, result) => {
              if (err) {
                console.warn('⚠️ brotli解压失败:', err.message);
                resolve(buffer.toString('utf8'));
              } else {
                resolve(result.toString('utf8'));
              }
            });
            break;
          default:
            resolve(buffer.toString('utf8'));
        }
      } catch (error) {
        console.warn('⚠️ 解压过程异常:', error.message);
        resolve(buffer.toString('utf8'));
      }
    });
  }

  /**
   * 验证HTTP方法
   */
  static isValidHttpMethod(method) {
    const validMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'];
    return validMethods.includes(method.toUpperCase());
  }

  /**
   * 验证路径
   */
  static isValidPath(path) {
    return path && path.startsWith('/');
  }

  /**
   * 清理代理相关请求头
   */
  static cleanProxyHeaders(headers) {
    const cleanedHeaders = { ...headers };
    delete cleanedHeaders['proxy-connection'];
    delete cleanedHeaders['proxy-authorization'];
    return cleanedHeaders;
  }

  /**
   * 构建HTTP响应头
   */
  static buildHttpResponseHeader(statusCode, statusMessage, headers) {
    let responseHeader = `HTTP/1.1 ${statusCode} ${statusMessage}\r\n`;
    
    // 转发响应头，跳过可能导致问题的头
    Object.keys(headers).forEach(key => {
      if (key.toLowerCase() !== 'transfer-encoding') {
        responseHeader += `${key}: ${headers[key]}\r\n`;
      }
    });
    responseHeader += '\r\n';
    
    return responseHeader;
  }

  /**
   * 获取内容类型判断是否为文本
   */
  static isTextContent(contentType) {
    if (!contentType) return false;
    
    return contentType.includes('text/') || 
           contentType.includes('application/json') || 
           contentType.includes('application/xml') ||
           contentType.includes('application/javascript');
  }

  /**
   * 生成错误响应
   */
  static createErrorResponse(statusCode, message) {
    return `HTTP/1.1 ${statusCode} ${message}\r\n\r\n${message}`;
  }

  /**
   * 解析URL
   */
  static parseUrl(urlString) {
    try {
      return new URL(urlString);
    } catch (error) {
      return null;
    }
  }

  /**
   * 格式化字节大小
   */
  static formatBytes(bytes) {
    if (bytes === 0) return '0 Bytes';
    
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  }

  /**
   * 格式化持续时间
   */
  static formatDuration(ms) {
    if (ms < 1000) return `${ms}ms`;
    if (ms < 60000) return `${(ms / 1000).toFixed(2)}s`;
    return `${(ms / 60000).toFixed(2)}m`;
  }
} 